package org.example.util.jwt;

import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;

import javax.crypto.SecretKey;
import java.security.Key;
import java.security.PublicKey;
import java.util.Date;
import java.util.Map;

public class JWTUtil {
    public static String generateToken(Map<String,Object> claims, Key key, Date expDate){
        return Jwts.builder()
                .claims(claims)
                .expiration(expDate)
                .signWith(key)
                .compact();
    }
    public static Map<String,Object> parseToken(String token,Key key){
        JwtParser jwtParser=null;
        if (key instanceof SecretKey){
            jwtParser=Jwts.parser()
                    .verifyWith((SecretKey) key)
                    .build();
        }else if(key instanceof PublicKey){
            jwtParser=Jwts.parser()
                    .verifyWith((PublicKey) key)
                    .build();
        }else{
            throw new IllegalArgumentException("invalid key type");
        }
        try {
            return jwtParser.parseSignedClaims(token).getPayload();
        }catch (Exception e){
            throw new ParseJWTException("解析jwt失败",e);
        }
    }
}
